from flask import Blueprint, request, jsonify, session, redirect
import api.user_api as user_api 



user = Blueprint('user',__name__)


#用户模块 user/list  user/login   user/register  user/changepwd
#路由配置


# 返回用户列表功能
@user.route('/list', methods=['get'])
def user_list():
    list = user_api.User_List()
    return jsonify(list)


# 注册功能
@user.route('/register', methods=['post'])
def user_register():
    data={'state':'', 'users':[]}
    username = request.form.get('username')
    password = request.form.get('password')
    # phone = request.form.get('phone')
    phone=''
    # 判断输入是否为空
    if username == '':
        data['state']="请输入用户名"
    elif password == '':
        data['state']="请输入密码"
    else:
        # 判断是否存在该用户名
        users = user_api.User_Find_Username(username)
        if users:
            data['state']="用户名已存在"
        else:
            user_api.User_Register(username, password, phone)
            user = user_api.User_Find_Username(username)
            session['id'] = user[0]['id']
            data['state']="用户创建"
            data['users']=user
    return jsonify(data)


# 登录功能
@user.route('/login', methods=['post'])
def user_login():
    data={'state':'', 'users':[]}
    if session.get('id'):
        id = session.get('id')
        user = user_api.User_Find_Id(id)
        data['state']="登录成功"
        data['users']=user
    else:
        username = request.form.get('username')
        password = request.form.get('password')
        # 查询是否存在该用户名，判断密码
        user = user_api.User_Find_Username(username)
        if user:
            if user[0]['password'] == password:
                session['id'] = user[0]['id']
                # session.permanent = True
                data['state']="登录成功"
                data['users']=user
            else:
                data['state']="密码错误"
        else:
            data['state']="用户不存在"
    return jsonify(data)


# 登出功能
@user.route('/logout', methods=['get'])
def user_logout():
    session.clear()
    return "退出账号"


# 查找用户
@user.route('/find', methods=['get'])
def user_find():
    info = request.args.get('info')
    list1 = user_api.User_Find_Id(info)
    list2 = user_api.User_Find_Username(info)
    list = list1 + list2
    return jsonify(list)


# 按名查找用户
@user.route('/findusername', methods=['get'])
def user_find_username():
    username = request.args.get('username')
    list = user_api.User_Find_Username(username)
    return jsonify(list)


# 按id查找用户
@user.route('/findid', methods=['get'])
def user_find_id():
    id = request.args.get('id')
    list = user_api.User_Find_Id(id)
    return jsonify(list)


#查询session 确认登录状态
@user.route('/state', methods=['get'])
def index():
    data={'state':'', 'users':[]}
    id = session.get('id')
    if id:
        user = user_api.User_Find_Id(id)
        data['users']=user
        data['state']="已登录"
    else:
        data['state']="未登录"
    return jsonify(data)



 

 




